import { BanList, classifyUrl } from "./BanList";
import { BASE_URL } from "./utils/common";
import { Config } from "./utils/config";

window.addEventListener("load", () => {
  window.pop = new PopIndex();
});

class PopIndex {
  // showListBtn: null | HTMLButtonElement = null;
  listContainer: null | HTMLDivElement =
    document.querySelector("#listContainer");
  con: null | HTMLSpanElement = document.getElementById("con");
  template: null | HTMLTemplateElement = document.querySelector("template");
  filterResult: null | HTMLInputElement = document.querySelector("#filter");

  addName = document.querySelector("#add1");
  addLink = document.querySelector("#add2");

  banList: BanList = new BanList();
  config: Config = new Config();
  //
  switchBtn1: null | HTMLInputElement = document.querySelector("#switch1");
  switchBtn2: null | HTMLInputElement = document.querySelector("#switch2");
  switchBtn3: null | HTMLInputElement = document.querySelector("#switch3");
  switchBtn4: null | HTMLInputElement = document.querySelector("#switch4");
  //
  // updateBtn: null | HTMLButtonElement =
  //   document.querySelector("#updateBanList");

  constructor() {
    this.init();
  }
  init() {
    this.banList.updateList().then(() => {
      this.banList
        .init((list) => this.showList(list))
        .then(() => {
          this.showList(this.banList.getList());
        });
    });

    this.eventHandler();

    this.setInitialStatus();
  }
  private globalEnable(val: boolean) {
    // console.log("this.globalEnable", val);

    this.exist(this.switchBtn2, (btn) => {
      btn.disabled = !val;
    });
    this.exist(this.switchBtn3, (btn) => {
      btn.disabled = !val;
    });

    this.exist(this.switchBtn4, (btn) => {
      btn.disabled = !val;
    });
  }
  setInitialStatus() {
    // this.config.initConfigFromStorage().then(() => {
    //   this.exist(this.switchBtn1, (switchBtn) => {
    //     const val = this.config.getEnable();
    //     switchBtn.checked = val;
    //     this.globalEnable(val);
    //   });
    //   this.exist(this.switchBtn2, (switchBtn) => {
    //     switchBtn.checked = this.config.getConfig().stopRedirect;
    //   });
    //   this.exist(this.switchBtn3, (switchBtn) => {
    //     switchBtn.checked = this.config.getConfig().removeIframe;
    //   });
    // });
    this.config.onChange((conf) => {
      this.exist(this.switchBtn1, (switchBtn) => {
        const val = conf.enable; //this.config.getEnable();
        switchBtn.checked = val;
        this.globalEnable(val);
      });
      this.exist(this.switchBtn2, (switchBtn) => {
        switchBtn.checked = conf.stopRedirect; //this.config.getConfig().stopRedirect;
      });
      this.exist(this.switchBtn3, (switchBtn) => {
        switchBtn.checked = conf.removeIframe; //this.config.getConfig().removeIframe;
      });
      this.exist(this.switchBtn4, (switchBtn) => {
        switchBtn.checked = conf.removeLogs; //this.config.getConfig().removeIframe;
      });
    });
  }
  private eventHandler() {
    // this.exist(this.addUrls, (addUrls) => {
    //   addUrls.addEventListener("keydown", (e) => {
    //     if (e.key === "Enter" && this.addUrls?.value) {
    //       this.add(this.addUrls.value);
    //       this.addUrls.value = "";
    //     }
    //   });
    // });
    // this.exist(this.updateBtn, (btn) => {
    //   btn.addEventListener("click", () => {
    //     this.banList.updateList();
    //   });
    // });
    this.exist(this.filterResult, (filter) => {
      filter.addEventListener("input", (e) => {
        fetch(
          BASE_URL +
            `/KeywordApi/getKeywordList?page=1&size=100&search=${
              (e as any).target.value
            }`
        )
          .then((res) => res.json())
          .then((res) => {
            this.showList(classifyUrl(res.list));
          });
        // const list = this.banList.getList();
        // this.showList(
        //   list.filter((val) => val.indexOf((e as any).target.value) > -1)
        // );
      });
    });

    this.exist(this.addName, (addName) => {
      this.exist(this.addLink, (addLink) => {
        addLink.addEventListener("keyup", (e) => {
          if ((e as KeyboardEvent).keyCode === 13) {
            const name = (addName as HTMLInputElement).value;
            const link = (addLink as HTMLInputElement).value;
            if (link && name) {
              fetch(
                BASE_URL + `/KeywordApi/addKeyword?url=${link}&keyName=${name}`,
                {
                  method: "POST",
                  headers: {
                    "content-type": "application/x-www-form-urlencoded",
                  },
                }
              ).then(() => {
                this.banList.updateList();
              });
            } else {
              alert("link or name not exist!");
            }
          }
        });
      });
    });

    this.exist(this.switchBtn1, (switchBtn) => {
      switchBtn.addEventListener("click", () => {
        // console.log(this.config.getConfig().enable, "before");
        this.config.setEnable(switchBtn.checked);
        this.globalEnable(switchBtn.checked);
        // console.log(this.config.getConfig().enable, "after");
      });
    });

    this.exist(this.switchBtn2, (switchBtn) => {
      switchBtn.addEventListener("click", () => {
        // console.log(this.config.getConfig().stopRedirect, "before");
        this.config.setRedirect(switchBtn.checked);
        // console.log(this.config.getConfig().stopRedirect, "after");
      });
    });

    this.exist(this.switchBtn3, (switchBtn) => {
      switchBtn.addEventListener("click", () => {
        // console.log(this.config.getConfig().removeIframe, "before");
        this.config.setRemoveIframe(switchBtn.checked);
        // console.log(this.config.getConfig().removeIframe, "after");
      });
    });

    this.exist(this.switchBtn4, (switchBtn) => {
      switchBtn.addEventListener("click", () => {
        // console.log(this.config.getConfig().removeIframe, "before");
        this.config.setRemoveLogs(switchBtn.checked);
        // console.log(this.config.getConfig().removeIframe, "after");
      });
    });
  }
  exist<T>(entity: T | null, success: (en: T) => void) {
    if (!entity) {
      console.trace("entity does not exist!", entity);
      return;
    }
    success(entity);
  }
  showList(list: string[]) {
    const frag = document.createDocumentFragment();
    list.forEach((val) => {
      this.exist(this.template, (template) => {
        const clon = template.content.cloneNode(true) as Element;
        const url = clon.querySelector(".url");
        this.exist(url, (url) => (url.textContent = val));
        const openBtn = clon.querySelector("li") as HTMLLIElement;
        openBtn.onclick = function () {
          window.open(val.replace(/\.\*$/, ""));
        };
        // const removeBtn = clon.querySelector(".removeBtn") as HTMLButtonElement;

        // const that = this;
        // removeBtn.onclick = function (e) {
        //   e.stopPropagation();
        //   that.remove(val);
        //   return false;
        // };

        // const copyBtn = clon.querySelector(".copyBtn") as HTMLButtonElement;
        // copyBtn.onclick = function (e) {
        //   e.stopPropagation();
        //   window.navigator.clipboard.writeText(val);
        //   return false;
        // };
        frag.appendChild(clon);
      });
    });
    this.exist(this.listContainer, (listContainer) => {
      listContainer.innerHTML = "";
      listContainer.append(frag);
    });
  }

  async add(url: string) {
    this.banList.addToList(url);
  }
  async remove(url: string) {
    this.banList.removeFromList(url);
  }
}
